//
//  704. 二分查找.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/15.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation

class Solution704 {
    // 有序数组，且没有重复的元素，一看就想到二分法
    func search(_ nums: [Int], _ target: Int) -> Int {
        var left = 0
        var right = nums.count - 1
        while left <= right {
            let mid = (left + right) / 2
            if nums[mid] < target {
                left = mid + 1
            } else if nums[mid] == target {
                return mid
            } else {
                right = mid - 1
            }
        }
        return -1
    }
    static func test() {
        let solution = Solution704()
        let nums = [-1,0,3,5,9,12]
        let result = solution.search(nums, 9)
        print(result)
    }
}
